package com.warmlight.voicepacket.ui.imlm.adapter;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.support.v4.app.FragmentActivity;
import android.text.TextPaint;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.umeng.analytics.MobclickAgent;
import com.warmlight.voicepacket.R;
import com.warmlight.voicepacket.base.SingleRecycleViewAdapter;
import com.warmlight.voicepacket.data.eventbus.NotifyMyPlaylist;
import com.warmlight.voicepacket.data.eventbus.PlayerServiceData;
import com.warmlight.voicepacket.http.HttpClient;
import com.warmlight.voicepacket.http.HttpConfig;
import com.warmlight.voicepacket.http.HttpUtils;
import com.warmlight.voicepacket.http.ResponseData;
import com.warmlight.voicepacket.ui.user.LoginRegistActivity;
import com.warmlight.voicepacket.ui.user.dialog.MySoundDialog;
import com.warmlight.voicepacket.ui.user.usercenter.LookUserCenterActivity;
import com.warmlight.voicepacket.utils.GlideRoundTransform;
import com.warmlight.voicepacket.utils.JSONUtils;
import com.warmlight.voicepacket.utils.MobClickHelper;
import com.warmlight.voicepacket.utils.SPUtils;
import com.warmlight.voicepacket.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Map;
import java.util.TreeMap;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.rong.imkit.RongIM;
import io.rong.imlib.model.Conversation;

public class TeaseAdapter extends SingleRecycleViewAdapter<Map<String,String>> {

    private TextPaint paint;
    private final RequestOptions requestOptions;
    private int isMine; //0 默认 1 自己  2 别人

    public TeaseAdapter(Context context) {
        super(context);
        paint = new TextPaint();
        requestOptions = new RequestOptions();
        requestOptions.transform(new GlideRoundTransform(mContext)).dontAnimate().placeholder(R.drawable.icon_roud_placeholder);
    }

    /**
     *
     * @param context
     * @param isMine 0 默认 1 自己  2 别人
     */
    public TeaseAdapter(Context context,int isMine) {
        super(context);
        paint = new TextPaint();
        requestOptions = new RequestOptions();
        requestOptions.transform(new GlideRoundTransform(mContext)).dontAnimate().placeholder(R.drawable.icon_roud_placeholder);
        this.isMine = isMine;
    }

    @Override
    public HashViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.adapter_tease_item,parent,false);
        HashViewHolder holder = new HashViewHolder(view);
        holder.putView(R.id.iv_feed);
        holder.putView(R.id.iv_play_state);
        holder.putView(R.id.tv_feed_content);
        holder.putView(R.id.iv_feed_anime);
        holder.putView(R.id.tv_feed_time);
        holder.putView(R.id.tv_audio_name);
        holder.putView(R.id.tv_time);
        holder.putView(R.id.tv_tease);
        holder.putView(R.id.tv_feed_zan);
        holder.putView(R.id.rl_xm);
        holder.putView(R.id.iv_sex);
        holder.putView(R.id.iv_private);
        holder.putView(R.id.iv_more);

        return holder;
    }

    /**
     * "list": [{
     "id": "1",
     "type": "1",
     "title": "玩皮凉鞋正品真皮男士休闲鞋",
     "url": "https:\/\/wanpi-img.oss-cn-shanghai.aliyuncs.com\/wanpi_audio/1001/20180807192637/avator.pcm",
     "duration": "0",
     "is_hot": "0",
     "is_like": false,
     "star_num": "0",
     "add_time": "08-07 11:26",
     "author": {
     "uid": "1001",
     "nickname": "波",
     "avator": "https:\/\/wanpi-img.oss-cn-shanghai.aliyuncs.com\/wanpi\/1001\/20180807212451\/avator.png"
     }
     }]
     * @param holder
     * @param position
     */
    @Override
    public void onBindViewHolder(final HashViewHolder holder, final int position) {
        final Map<String, String> item = getItem(position);
        final String id = item.get("id");
        String type = item.get("type");
        String title = item.get("title");
        final String url = item.get("url");
        String duration = item.get("duration");
        String is_hot = item.get("is_hot");
        String is_like = item.get("is_like");
        String star_num = item.get("star_num");
        final String add_time = item.get("add_time");
        String author = item.get("author");
        String is_open = item.get("is_open");
        //
        String uid = "";
        String nickname = "";
        String avator = "";
        String sex = "0";
        if (!TextUtils.isEmpty(author)) {
            ArrayList<Map<String, String>> listMapByJson = JSONUtils.getListMapByJson(author);
            if (listMapByJson.size()>0) {
                Map<String, String> map = listMapByJson.get(0);
                uid = map.get("uid");
                nickname = map.get("nickname");
                avator = map.get("avator");
                sex = map.get("sex");
            }
        }
        //
        final String isplay = item.get("isplay");

        final ImageView iv_feed = (ImageView) holder.findView(R.id.iv_feed);
        final ImageView iv_play_state = (ImageView) holder.findView(R.id.iv_play_state);
        final TextView tv_feed_content = (TextView) holder.findView(R.id.tv_feed_content);
        final ImageView iv_feed_anime = (ImageView) holder.findView(R.id.iv_feed_anime);
        TextView tv_feed_time = (TextView) holder.findView(R.id.tv_feed_time);
        final TextView tv_audio_name = (TextView) holder.findView(R.id.tv_audio_name);
        TextView tv_time = (TextView) holder.findView(R.id.tv_time);
        TextView tv_tease = (TextView) holder.findView(R.id.tv_tease);
        final TextView tv_feed_zan = (TextView) holder.findView(R.id.tv_feed_zan);
        final RelativeLayout rl_xm = (RelativeLayout) holder.findView(R.id.rl_xm);
        ImageView iv_sex = (ImageView) holder.findView(R.id.iv_sex);
        ImageView iv_private = (ImageView) holder.findView(R.id.iv_private);
        ImageView iv_more = (ImageView) holder.findView(R.id.iv_more);
        if (isMine==1){
            iv_more.setVisibility(View.VISIBLE);
            if (!TextUtils.equals("1",is_open)){
                iv_private.setVisibility(View.VISIBLE);
            }else{
                iv_private.setVisibility(View.GONE);
            }

        }else{
            iv_private.setVisibility(View.GONE);
            iv_more.setVisibility(View.GONE);
        }



        final String finalUid1 = uid;
        tv_audio_name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isMine == 0) {
                    Intent intent = new Intent(mContext, LookUserCenterActivity.class);
                    intent.putExtra("uid", finalUid1);
                    intent.putExtra("type","sound");
                    mContext.startActivity(intent);
                }
            }
        });

        iv_more.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MySoundDialog mySoundDialog = new MySoundDialog();
                mySoundDialog.setOnTypeClick(new MySoundDialog.OnTypeClick() {
                    @Override
                    public void type(String type) {
                        if (TextUtils.equals("del",type)){
                            deleteItem(position);
                        }
                    }
                });
                mySoundDialog.show(((FragmentActivity)mContext).getSupportFragmentManager(),"dialog");
            }
        });

        if (requestOptions != null) {
            Glide.with(mContext).load(avator).apply(requestOptions)
                    .into(iv_feed);
        }

        if (TextUtils.equals("0",sex)){
            iv_sex.setVisibility(View.GONE);
        }else if (TextUtils.equals("1",sex)){
            iv_sex.setVisibility(View.VISIBLE);
            iv_sex.setImageResource(R.drawable.icon_im_boy);
        }else{
            iv_sex.setVisibility(View.VISIBLE);
            iv_sex.setImageResource(R.drawable.icon_im_girl);
        }

        tv_feed_content.setText(title);
        tv_feed_time.setText(duration+"s");
        tv_audio_name.setText(nickname);
        tv_time.setText(add_time);
        tv_feed_zan.setText(star_num);

        paint = tv_time.getPaint();

        float v = this.paint.measureText(add_time);
        float a = 0;
        if (isMine==1 && !TextUtils.equals("1",is_open)){
            a = mContext.getResources().getDimension(R.dimen.dp40);
        }else {
            a = mContext.getResources().getDimension(R.dimen.dp10);
        }
        tv_audio_name.setPadding(0,0, (int) (v+a),0);


        String loginUid = SPUtils.getLoginUid();
        if (TextUtils.equals(loginUid,uid)){
            tv_tease.setVisibility(View.GONE);
        }else{
            tv_tease.setVisibility(View.VISIBLE);
        }

        if (isMine == 2){
            tv_tease.setVisibility(View.GONE);
        }


        if (TextUtils.equals("1",isplay)) {
            iv_play_state.setImageResource(R.drawable.icon_audio_pause);
            // 放动画
            iv_feed_anime.setBackgroundResource(R.drawable.anime_playing);
            AnimationDrawable drawable = (AnimationDrawable) iv_feed_anime.getBackground();

            drawable.start();
        } else {
            iv_play_state.setImageResource(R.drawable.icon_audio_play);
            // 暂停动画
            Drawable d = iv_feed_anime.getBackground();
            if (d instanceof AnimationDrawable) {
                ((AnimationDrawable) iv_feed_anime.getBackground()).stop();
            }
//            holder.iv_feed_anime.setImageResource(R.drawable.icon_audio_play);
            iv_feed_anime.setBackgroundResource(R.drawable.frame3);
        }

        if (TextUtils.equals("true",is_like)){
            Drawable drawable = mContext.getResources().getDrawable(R.drawable.icon_tease_zan_yes);
//一定要加这行！！！！！！！！！！！
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            tv_feed_zan.setCompoundDrawables(drawable,null,null,null);
        }else{
            Drawable drawable = mContext.getResources().getDrawable(R.drawable.icon_tease_zan_no);
//一定要加这行！！！！！！！！！！！
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            tv_feed_zan.setCompoundDrawables(drawable,null,null,null);
        }

        //*******************点击事件***********************
        final String finalNickname = nickname;
        final String finalUid = uid;
        tv_tease.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转到聊天页面
//                 *
// * @param context          应用上下文。
// * @param conversationType 会话类型。
// * @param targetId         根据不同的 conversationType，可能是用户 Id、群组 Id 或聊天室 Id。
// * @param title            聊天的标题，开发者可以在聊天界面通过 intent.getData().getQueryParameter("title") 获取该值, 再手动设置为标题。
                if (SPUtils.isLogined()){
                    if (!TextUtils.isEmpty(finalUid)) {
                        MobclickAgent.onEvent(mContext, MobClickHelper.VSOCIAL_CHAT, MobClickHelper.VSOCIAL_CHAT + "_" + id + "_" + finalUid);
                        RongIM.getInstance().startConversation(mContext, Conversation.ConversationType.PRIVATE, finalUid, finalNickname);
                    }else{
                        ToastUtil.showShort(mContext,"该用户不存在");
                    }
                }else{
                    //如果未登录，就去登录。然后刷新整个页面
                    Intent intent1 = new Intent(mContext, LoginRegistActivity.class);
                    mContext.startActivity(intent1);
                }
            }
        });

        tv_feed_zan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!SPUtils.isLogined()){
                    Intent intent = new Intent(mContext, LoginRegistActivity.class);
                    mContext.startActivity(intent);
                }else {
                    MobclickAgent.onEvent(mContext, MobClickHelper.VSOCIAL_LIKE,MobClickHelper.VSOCIAL_LIKE+"_"+id+"_"+ finalUid);
                    star(position, tv_feed_zan);
                }
            }
        });

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(TextUtils.equals("1",isplay)){
//                    iv_play_state.setImageResource(R.drawable.icon_audio_play);
//                    data.setPlaying(false);
                    item.put("isplay","0");

                    notifyDataSetChanged();

//                    Drawable d = iv_feed_anime.getDrawable();
//                    if(d instanceof AnimationDrawable){
//                        ((AnimationDrawable)iv_feed_anime.getDrawable()).stop();
//                        iv_feed_anime.setImageResource(R.drawable.frame3);
//                    }

                    EventBus.getDefault().post(new PlayerServiceData(PlayerServiceData.PAUSE,url));
                }else{

//                    clearPlay();
//                    if(mLastData != null && mLastView != null && mLastAnime != null){
//                        mLastView.setImageResource(R.drawable.icon_audio_play);
//                        mLastData.setPlaying(false);
//                        Drawable d = mLastAnime.getDrawable();
//                        if(d instanceof AnimationDrawable){
//                            ((AnimationDrawable)mLastAnime.getDrawable()).stop();
//                            mLastAnime.setImageResource(R.drawable.frame3);
//                        }
//                    }
                    if (isMine == 1) {
                        MobclickAgent.onEvent(mContext, MobClickHelper.PROFILE_VOICE_PLAY, id);
                    }else if (isMine == 2){
                        MobclickAgent.onEvent(mContext,MobClickHelper.GSTATE_VOICE_PLAY, finalUid + "-"+id);
                    }

                    EventBus.getDefault().post(new PlayerServiceData(PlayerServiceData.PLAY,url));

                    playItem(position);

                    iv_play_state.setImageResource(R.drawable.icon_audio_pause);
                    // 放动画
                    iv_feed_anime.setBackgroundResource(R.drawable.anime_playing);
                    AnimationDrawable drawable = (AnimationDrawable) iv_feed_anime.getBackground();

                    drawable.start();
//                    iv_play_state.setImageResource(R.drawable.icon_audio_pause);
////                    data.setPlaying(true);
//                    item.put("isplay","1");
//
//                    iv_feed_anime.setImageResource(R.drawable.anime_playing);
//                    ((AnimationDrawable)iv_feed_anime.getDrawable()).start();

//                    mLastView = holder.iv_play_state;
//                    mLastData = data;
//                    mLastAnime = holder.iv_feed_anime;

                    //FIXME 没时间了，先这么做。什么手段都先用着
//                    TempData.mLastAnime = holder.iv_feed_anime;
//                    TempData.mLastData = data;
//                    TempData.mLastView = holder.iv_play_state;

                }
            }
        });
    }

    private void deleteItem(final int position) {
        Map<String, String> item = getItem(position);
        String id = item.get("id");
        String url = HttpConfig.DEL_AUDIO;
        TreeMap<String,String> treeMap = new TreeMap<>();
        treeMap.put("audio_id",id);
        HttpClient.getInstance().postRxAndroidAES(url,treeMap)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseData>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseData responseData) {
                        if (HttpUtils.isCodeSuccess(responseData.getCode())){
                            removeItem(position);
                            ToastUtil.showShort(mContext,"删除成功");
                            EventBus.getDefault().post(new NotifyMyPlaylist("net"));
                        }else{
                            ToastUtil.showShort(mContext,responseData.getMsg());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        ToastUtil.showShort(mContext,"网络异常，请稍后重试");
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void star(final int position, final TextView tv_feed_zan) {
        final Map<String, String> item = getItem(position);
        final String is_like = item.get("is_like");
        String id = item.get("id");
        String url = HttpConfig.MEMBERAUDIOSTAR;
        final TreeMap<String,String> treeMap = new TreeMap<>();
        treeMap.put("member_audio_id",id);
        if (TextUtils.equals("true",is_like)){
            treeMap.put("status","-1");
        }else{
            treeMap.put("status","1");
        }
        HttpClient.getInstance().postRxAndroidAES(url,treeMap)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseData>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseData responseData) {
                        if (HttpUtils.isCodeSuccess(responseData.getCode())){

                            if (TextUtils.equals("true",is_like)){
//                                String text = tv_feed_zan.getText().toString();
                                String star_num = item.get("star_num");
                                int a = Integer.valueOf(star_num)-1;
                                tv_feed_zan.setText(a+"");
                                getItem(position).put("star_num",a+"");
                                getItem(position).put("is_like","false");
                                Drawable drawable = mContext.getResources().getDrawable(R.drawable.icon_tease_zan_no);
//一定要加这行！！！！！！！！！！！
                                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                                tv_feed_zan.setCompoundDrawables(drawable,null,null,null);
                            }else{
                                String star_num = item.get("star_num");
//                                String text = tv_feed_zan.getText().toString();
                                int a = Integer.valueOf(star_num)+1;
                                tv_feed_zan.setText(a+"");
                                getItem(position).put("star_num",a+"");
                                getItem(position).put("is_like","true");
                                Drawable drawable = mContext.getResources().getDrawable(R.drawable.icon_tease_zan_yes);
//一定要加这行！！！！！！！！！！！
                                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                                tv_feed_zan.setCompoundDrawables(drawable,null,null,null);
                            }


                        }else{
                            ToastUtil.showShort(mContext,responseData.getMsg());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    public void clearPlay(){
        for (int i=0;i<getItemCount();i++){
            getItem(i).put("isplay","0");
        }
        notifyDataSetChanged();
    }

    public void playItem(int position){
        for (int i=0;i<getItemCount();i++){
            getItem(i).put("isplay","0");
        }
        getItem(position).put("isplay","1");
        notifyDataSetChanged();
    }
}
